<template>
    <a-select
        :allowClear="allowClear"
        show-search
        v-model:value="value"
        style="width: 100%"
        :filter-option="false"
        @change="change"
        :options="options"
        @search="remoteMethod"
        :placeholder="placeholder"
        :fieldNames="{label : labelField, value : valueField, options : optionsField}"
    >
        <template v-if="loading" #notFoundContent>
            <a-spin size="small" />
        </template>
        <template v-else-if="!keyword" #notFoundContent>
            <span>{{ $c('please', 'input') }}</span>
        </template>
    </a-select>
</template>

<script lang='ts' setup>
    import { ref } from "vue"
    import { debounce } from 'lodash-es';

    type QeryType = string|string[]|number|number[]

    const props = withDefaults(defineProps<{
        modelValue : QeryType,
        level? : number,
        valueField? : string,
        labelField? : string,
        optionsField? : string,
        fetch : {
            (key:QeryType, init?:boolean) : Promise<any[]>
        },
        size? : string,
        initQuery? : string,
        clearable? : boolean,
        placeholder? : string,
        allowClear? : boolean
    }>(), {
        valueField : 'id',
        labelField : 'name',
        optionsField : 'children',
    })

    const emit = defineEmits<{
        (e : 'change', value : any) : void,
        (e : 'update:modelValue', value : any) : void
    }>()

    const loading = ref(false)

    const value = ref(props.modelValue)
    const keyword = ref('')

    const options = ref<any[]>([])

    const remoteMethod = debounce((query:string) => {
        keyword.value = query
        doFetch(query, false)
    }, 300)

    const doFetch = (query:QeryType, init:boolean) => {
        if(loading.value) return
        if(query !== '') {
            loading.value = true
            options.value.splice(0)
            props.fetch(query, init).then(rows => {
                loading.value = false
                options.value = rows || []
            })
        }
    }

    // async function remoteMethod(query:string) {
    //     if(loading.value) return
    //    if(query !== '') {
    //         loading.value = true
    //         options.value.splice(0)
    //         const rows = await props.fetch(query)
    //         loading.value = false
    //         options.value = rows
    //    }
    // }

    function change(e) {
        emit('update:modelValue', e)
        emit('change', e)
    }

    if(props.modelValue) {
        doFetch(props.modelValue, true)
    }
    
    

    
</script>